﻿using Bridge.Workflow.Domain;
using Bridge.Workflow.EntityFrameworkCore.Persistence;
using System;
using System.Threading.Tasks;
using Users;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Uow;
using Volo.Abp.Users;
using WorkflowCore.Interface;
using WorkflowCore.Models;

namespace Bridge.Workflow.Application
{
    public class CreateUserStepBody : StepBody, ITransientDependency
    {
        private const string ActionName = "AuditEvent";
        private readonly IUnitOfWork _unitOfWork;
        private readonly IAbpPersistenceProvider _abpPersistenceProvider;
        private readonly IUserService _userService;
        private readonly ICurrentUser _currentUser;
        private readonly IRepository<PersistedWorkflowAuditor, string> _auditorRepository;

        public CreateUserStepBody
            (IUnitOfWork unitOfWork,
            IUserService userService,
            IAbpPersistenceProvider abpPersistenceProvider,
            ICurrentUser currentUser,
            IRepository<PersistedWorkflowAuditor, string> auditorRepository)
        {
            _unitOfWork = unitOfWork;
            _abpPersistenceProvider = abpPersistenceProvider;
            _userService = userService;
            _currentUser = currentUser;
            _auditorRepository = auditorRepository;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public override ExecutionResult Run(IStepExecutionContext context)
        {
            //return ExecutionResult.Next();
            return ExecutionRunAsync(context).Result;
        }

        /// <summary>
        /// 生成审核记录
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task<ExecutionResult> ExecutionRunAsync(IStepExecutionContext context)
        {
            if (!context.ExecutionPointer.EventPublished)
            {
                var workflow = await _abpPersistenceProvider.GetPersistedWorkflow(context.Workflow.Id);
                        
                var auditUserResult = await _userService.GetUserById(workflow.CreatorId.Value);
                if(auditUserResult.Code == 0)
                {
                    throw new Exception("未找到审批用户");
                }
                var auditUser = auditUserResult.Result;
                //添加审批人
                var key = Guid.NewGuid().ToString();
                var result = await _abpPersistenceProvider.InsertAuditor(new PersistedWorkflowAuditor(key)
                {
                    WorkflowId = workflow.Id,
                    ExecutionPointerId = context.ExecutionPointer.Id,
                    Status = EnumAuditStatus.UnAudited,
                    //AuditTime = DateTime.Now,
                    UserId = auditUser?.Id ?? Guid.Empty,
                    TenantId = workflow.TenantId,
                    UserIdentityName = auditUser?.Name,
                    CreationTime = DateTime.Now,
                    Remark = string.Empty,
                    CreatorId = auditUser?.Id,
                });
                await _unitOfWork.SaveChangesAsync();
                //DateTime effectiveDate = DateTime.MinValue;
                //return ExecutionResult.WaitForEvent(ActionName, Guid.NewGuid().ToString(), effectiveDate);
                return ExecutionResult.WaitForEvent(ActionName, key, DateTime.MinValue);
            }
          
            return ExecutionResult.Next();
        }
    }
}
